<template>
  <div class="home">
    <div class="box" v-if="imgshow">
      <div class="showimg">
        <img :src="autoImg" alt="" />
      </div>
      <van-uploader :after-read="afterRead" />
    </div>
    <div class="imgbox" v-if="!imgshow && smallimg" ref="canvasDom">
      <img class="bigimg" :src="imgUrl" alt="" />
      <img class="smallimg" src="../assets/base_01.png" alt="" />
    </div>
    <div class="imgbox" v-if="!imgshow && !smallimg">
      <img class="bigimg" :src="imgUrl" alt="" />
    </div>
    <van-overlay :show="ifShow" z-index="1000" class-name="zhezhao">
      <van-loading size="35px" text-size="24px" color="#fff" vertical
        >赵狗子图片生成中...</van-loading
      >
    </van-overlay>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import { Button, NavBar, Uploader, Overlay, Loading } from 'vant';

import html2canvas from 'html2canvas';
export default defineComponent({
  name: 'Home',
  components: {
    [Button.name]: Button,
    [NavBar.name]: NavBar,
    [Uploader.name]: Uploader,
    [Overlay.name]: Overlay,
    [Loading.name]: Loading,
  },
  setup() {
    const imgshow = ref(true);
    const imgUrl = ref('');
    const canvasDom = ref<HTMLElement>();
    const imgH = ref();
    const imgW = ref();
    const smallimg = ref(true);
    const autoImg = ref();
    const ifShow = ref(false);

    const afterRead = (file: any) => {
      // 此时可以自行将文件上传至服务器
      imgshow.value = !imgshow.value;
      imgUrl.value = file.content;
      let image = new Image();
      ifShow.value = true;
      image.src = file.content;
      image.onload = () => {
        imgH.value = image.height;
        imgW.value = image.width;
        toImage();
      };
    };

    // 转换方法
    const toImage = () => {
      let width = document.body.clientWidth;
      let height = (width * imgH.value) / imgW.value;
      setTimeout(() => {
        if (canvasDom.value) {
          html2canvas(canvasDom.value, {
            backgroundColor: null,
            width: width,
            height: height,
          }).then((canvas) => {
            let dataURL = canvas.toDataURL('image/png');
            imgUrl.value = dataURL;
            smallimg.value = false;
            ifShow.value = false;
          });
        }
      });
    };

    onMounted(() => {
      autoImg.value = require(`../assets/${Math.ceil(Math.random() * 9)}.jpg`);
    });

    return {
      afterRead,
      imgshow,
      imgUrl,
      canvasDom,
      imgH,
      imgW,
      smallimg,
      autoImg,
      ifShow,
    };
  },
});
</script>

<style lang="less" scoped>
.zhezhao {
  display: flex;
  justify-content: center;
  align-items: center;
}
.showimg {
  width: 90%;
  margin: 5%;
  img {
    width: 100%;
    border-radius: 5px;
  }
}
.imgbox {
  position: relative;

  .bigimg {
    width: 100%;
  }
  .smallimg {
    width: 100%;
    position: absolute;
    z-index: 100;
    left: 0;
    top: 10.06rem;
  }
}
</style>
